<template>
  <Main class="mainPage">
    <template #header>
      <!-- 头部 -->
      <div class="mainPage-header">
        <div class="header">
          <div class="left">
            <el-icon size="17" color="#79bbff"><Notebook /></el-icon>
            分类：{{ activetreeList[0].deptName }}
          </div>
          <div class="right">
            <el-button
              type="primary"
              :icon="isFormVisible ? 'Filter' : 'Search'"
              @click="() => (isFormVisible = !isFormVisible)"
              >{{ isFormVisible ? '隐藏' : '查询' }}</el-button
            >
            <el-button @click="handleAddOrEdit" icon="Plus">新增</el-button>
          </div>
        </div>

        <div :class="['serachForm', isFormVisible ? '' : 'close']">
          <SerachForm :serachKey="serachKey" @updateSerach="serachTable" />
        </div>
      </div>
    </template>

    <!-- 表格列表 -->
    <template v-if="emrPageShare.tableList?.length" #default>
      <el-table :data="emrPageShare.tableList" border>
        <!-- @selection-change="handleSelectionChange"   // 批量选择-->
        <el-table-column type="index" label="序号" width="42" />
        <!-- <el-table-column type="selection" width="40" /> -->
        <el-table-column prop="docTempName" label="标题" />
        <el-table-column prop="deptName" label="归属机构" />
        <el-table-column prop="docTempTypeName" label="分类" />
        <el-table-column abel="状态" width="80">
          <template #default="scope">
            {{ scope.row.docTempStatus == '1' ? '正常' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="83">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleAddOrEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click.stop="handleRemove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分页 -->
    <template v-if="emrPageShare.tableList?.length" #pageFooter>
      <div class="table-footer">
        <!-- <div>
          <el-button @click="handleRemove">批量删除</el-button>
          <el-button @click="clearSelection()">清空选择</el-button>
        </div> -->
        <el-pagination
          small
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="emrPageShare.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="emrPageShare.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="emrPageShare.totalPage"
        >
        </el-pagination>
      </div>
    </template>

    <!-- 数据为空的状态 -->
    <el-empty v-if="!emrPageShare.tableList?.length" description="暂无数据" :image-size="150" style="height: 100%"></el-empty>
  </Main>
</template>

<script setup lang="ts">
  import { Ref, ref, reactive, getCurrentInstance, watch } from 'vue'
  import { ElTable } from 'element-plus'
  import { useRouter } from 'vue-router'
  // 自定义组件
  import SerachForm from '../../components/common/serachForm.vue'

  // 接收父组件值
  // const props = defineProps({
  //   data: {
  //     type: Object,
  //     default: {},
  //   },
  // })

  // 更新父组件方法
  let $emit = defineEmits<{
    (e: 'updateDocTempJson', bol: boolean, flag: string): void
  }>()

  // 配置类型约束
  import { IPageShare, ISerachKey, ISortForm } from '../../interface/pageShare'
  // 仓库数据以及解构 store的配置数据
  import { useEmrPageShare } from '../../store/emrPageShare'
  const emrPageShare: IPageShare = useEmrPageShare()

  const { proxy } = getCurrentInstance() as any,
    router = useRouter()
  let isFormVisible: Ref<boolean> = ref(false), // 是否开启查询栏
    dialogvisible: Ref<boolean> = ref(false), // 添加分类数据开启和关闭
    activetreeList: any = reactive([]), // 当前下所有的分类
    // multipleTableRef = ref<InstanceType<typeof ElTable>>(), // 表格ref
    sortForm: ISortForm = reactive({
      // 弹层回填数据
      type: '',
      parentId: '',
      fatherName: '',
      id: '',
      name: '',
      code: '',
    }),
    serachKey: ISerachKey[] = reactive([
      // 分类对应的表格查询关键字
      { label: '标题', type: 'text', value: '' },
      { label: '分类', type: 'dropDown', value: '', list: [] },
      {
        label: '状态',
        type: 'dropDown',
        value: '',
        list: [
          { label: '正常', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
    ])
  // 筛选科室分类
  for (let obj of JSON.parse(window.sessionStorage.DictStore).baseDict) {
    if (obj.dictCode == 'FH0135') {
      serachKey[1].list.push({
        label: obj.dictItemName,
        value: obj.dictItemCode,
      })
    }
  }

  // 监听更新对应数据
  watch(
    (): any => [emrPageShare.activetreeList, dialogvisible.value],
    (): any => {
      if (!!emrPageShare.activetreeList) {
        activetreeList = []
        activetreeList.push(emrPageShare.activetreeList)
      }
      // if (!!props.data) {
      //   serachKey[1].list = props.data[1].childList
      // }
      if (!dialogvisible.value) {
        sortForm.type = ''
        sortForm.parentId = ''
        sortForm.fatherName = ''
        sortForm.id = ''
        sortForm.name = ''
        sortForm.code = ''
      }
    },
    {
      immediate: true,
      deep: true,
    }
  )

  // 通过关键子查询
  const serachTable = (flag?: String): void => {
    let params: any = {}
    for (let obj of serachKey) {
      if (!flag) {
        switch (obj.label) {
          case '标题':
            params.docTempName = obj.value
            break
          case '分类':
            params.dictItemCode = obj.value
            break
          case '状态':
            params.docTempStatus = obj.value
            break
        }
      } else {
        // 重置
        obj.value = ''
      }
    }
    emrPageShare.fetchOrganizationTable(proxy, params)
  }

  // 新增或编辑
  const handleAddOrEdit = (flag?: any): void => {
    let data: string = !!flag && !!flag.docTempJson ? (JSON.stringify(flag) as string) : ''
    $emit('updateDocTempJson', true, data)
    // isTmplEditVisible.value = true
    // docTempJson.value =  !!flag && !!flag.docTempJson ? (JSON.stringify(flag) as string) : ''
    // router.push({ path: '/emrEdit', query: { data: !!flag && !!flag.docTempJson ? (JSON.stringify(flag) as string) : '' } })
  }

  // 删除表格数据（单行或者批量删除）
  const handleRemove = (flag?: any): void => {
    const url: string = APP_GLOBAL.API['EMR']['emr-template-delete']
    proxy.$http
      .requestJSON('post', url, {
        docTempId: flag.docTempId,
      })
      .then((res: any) => {
        if (res.message == '操作成功') {
          emrPageShare.fetchOrganizationTable(proxy)
        }
      })
  }

  // 清空所有选择
  // const clearSelection = (): void => {
  //   multipleTableRef.value!.clearSelection()
  // }

  // 批量选择
  // const handleSelectionChange = (flag: any): void => {
  //   // multipleSelection.value = flag
  // }

  // 修改分页
  const handleSizeChange = (val: number) => {
    emrPageShare.$patch((state: IPageShare): void => {
      state.pageSize = val
    })
    emrPageShare.fetchOrganizationTable(proxy)
  }
  const handleCurrentChange = (val: number) => {
    emrPageShare.$patch((state: IPageShare): void => {
      state.pageNum = val
    })
    emrPageShare.fetchOrganizationTable(proxy)
  }
</script>

<style lang="scss" scoped>
  .mainPage {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    .serachForm {
      padding: 10px 0;
      transition: all 0.2s;
      &.close {
        height: 0;
        overflow: hidden;
        padding: 0;
      }
    }
    &-header {
      width: 100%;
      .header {
        display: flex;
        justify-content: space-between;
        padding: 6px 0;
        margin: -10px 0 0;
        border-bottom: 1px solid #d8dce5;
        align-items: center;
        .left,
        .right {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #333;
        }
      }
    }
    .table-footer {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .drawerClose {
    position: absolute;
    top: 15px;
    right: 15px;
    cursor: pointer;
    font-size: 22px;
    color: #777777;
  }
</style>
